package com.atguigu.flink.chapter05.transform;

import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/1/12 15:18
 */
public class Flink05_KeyBy {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        DataStreamSource<Integer> stream = env.fromElements(1, 3, 8, 4, 10);
        
        stream
            .keyBy(new KeySelector<Integer, Integer>() {
                @Override
                public Integer getKey(Integer value) throws Exception {
                    return value % 2 ;
                }
                
            })
            .print();  // 2
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
new KeyGroupStreamPartitioner<>(
                                keySelector,
                                StreamGraphGenerator.DEFAULT_LOWER_BOUND_MAX_PARALLELISM)

128

0或1  128  2
 KeyGroupRangeAssignment.assignKeyToParallelOperator(
                key, maxParallelism, numberOfChannels);


128  2  [0, 128)
computeOperatorIndexForKeyGroup(
                maxParallelism, parallelism, assignToKeyGroup(key, maxParallelism));
            
                  0或1  128
            assignToKeyGroup(key, maxParallelism)   [0, 128)
                    0或1  128
                computeKeyGroupForKeyHash(key.hashCode(), maxParallelism); [0, 128)

                    MathUtils.murmurHash(keyHash) % maxParallelism; // [0, 128)


    [0,128) * 2 / 128 =
    小于64的值乘以2 小于128 除以128 = 0
    大于等于64的值乘以2 大于128 除以128 = 1
    keyGroupId * parallelism / maxParallelism;
 */